<?php
// Thesis - Dr Worm: Using Mobile Phones in Lectures
// Written by Kenny Jong, Wilson Ong, Adam Letherbarrow
// Adapted from John Shepherd's php implementation for use in COMP3311

require("lib/defs.php"); //libs("util");
session_start(); 
$db = dbConnect(DBCONN);  
$thisURL = setURL();

// Parameters

$v = getParams(array(
   'classid'    => array("string","optional"),
   'question'    => array("string","optional"),
   'questionList'    => array("string","optional"),
   'questionID'    => array("string","optional"),
   'questionType'    => array("string","optional"),
   'answer'    => array("string","optional"),
	'error'      => array("string","optional")
));

if (($v["classid"] != "") && ($v["question"] != "")) {
   askQuestion($db,$v["classid"],$v["question"]);
} elseif (($v["questionID"] != "") && ($v["answer"] != "") && ($v["questionType"] != "")) {
   submitAnswer($db, $v["questionID"],$v["questionType"],$v["answer"]);
}

// Computation

#allow anonymous access
if (!isLoggedIn()) goto("session/login.php");

// Output

//echo startPage(userCourseName());
echo startPage("Student");
echo "<noscript>This requires javascript to run properly</noscript>";
getQuestions($db,userClassID());
echo displayQuestions();
echo displaySelectedQuestion();

echo endPage(false);

// Helpers

function askQuestion($db,$classid,$question)
{
   $sql = "insert into Enquiry (class, response) values (%d,%s)";
   dbQuery($db,mkSQL($sql,$classid,$question));
}

function submitAnswer($db,$questionID,$type,$answer)
{
   switch ($type) {
      case "MCQ":
         $sql = "insert into Response (question, response) values";
         $answers = explode("&",$answer);
         for ($i = 0; $i < count($answers); $i++) {
            $sql .= " (".$questionID.",'".$answers[$i]."')";
            if ($i < (count($answers) - 1)) {
               $sql .= ",";
            }
         }
         dbQuery($db,mkSQL($sql));
         break;
         
      case "Open":
         $sql = "insert into Response (question, response) values (%d,%s)";
         dbQuery($db,mkSQL($sql,$questionID,$answer));
         break;
         
      case "TFQ":
         $sql = "insert into Response (question, response) values (%d,%s)";
         dbQuery($db,mkSQL($sql,$questionID,$answer));
         break;
         
      default:
         break;
   }
   
   $_SESSION["answeredQuestions"][] = $questionID;
}

function getQuestions($db,$classid)
{
   $sql = "select id,number,qtype,description from RetrieveQuestions(%d)";
   $res = dbQuery($db,mkSQL($sql,$classid));
   
   $tempQuestions = array();
   while ($tuple = dbNext($res)) {
      $tempQuestion = array("qID" => 0,
               "qNum" => 0,
               "qType" => "Open",
               "qDescrip" => "",
               "possAnswers" => array());
      $tempQuestion["qID"] = $tuple["id"];
      $tempQuestion["qNum"] = $tuple["number"];
      $tempQuestion["qType"] = $tuple["qtype"];
      $tempQuestion["qDescrip"] = $tuple["description"];
      $tempQuestions[] = $tempQuestion;
   }
   $_SESSION["questions"] = $tempQuestions;
   $question = array(
               "qID" => 0,
               "qNum" => 0,
               "qType" => "Open",
               "qDescrip" => "",
               "possAnswers" => array());
   for ($i = 0; $i < count($_SESSION["questions"]); $i++) {
      $question = $_SESSION["questions"][$i];
      //echo $question["qDescrip"]."<br />";
   }
   
   for ($i = 0; $i < count($_SESSION["questions"]); $i++) {
      $questionID = $_SESSION["questions"][$i]["qID"];
      $sql = "select * from RetrievePossibleAnswers(%d)";
      $res = dbQuery($db,mkSQL($sql,$questionID));
      
      $tempAnswers = array();
      while ($tuple = dbNext($res)) {
         if (count($tuple) > 0) {
            $tempAnswers[] = $tuple[0];
         }
      }
      
      $_SESSION["questions"][$i]["possAnswers"] = $tempAnswers;
      
      /*if (count($_SESSION["questions"][$i]["possAnswers"])) {
         echo $_SESSION["questions"][$i]["possAnswers"][0];
      }*/
   }
   
   return 0;
}

function displayQuestions()
{
   global $v;

   $questionStrings = array();
   for ($i = 0; $i < count($_SESSION["questions"]); $i++) {
      $questionID = $_SESSION["questions"][$i]["qID"];
      $questionNum = $_SESSION["questions"][$i]["qNum"];
      if (notAnswered($questionID)) {
      //echo $questionNum;
      //$tempString = "Question ".$questionNum;
      //$questionStrings[] = $tempString;
         $questionStrings[] = $questionNum;
      } else {
         $questionStrings[] = $questionNum." (Answered)";
      }
   }
   
   $questionIndex = 0;
   if ($v["questionList"] == "") {
      $question = findFirstUnansweredIndex();
      //echo $questionIndex;
      if ($question >= 0) {
         $questionIndex = $_SESSION["questions"][$question]["qNum"];
      }
   } else {
      $questionIndex = $v["questionList"];
   }
   
   $html = startForm("","selectQuestion").
            selectFromList("questionList",$questionIndex,$questionStrings,"","onchange='loadQuestion(this)'").
            "<noscript>".inputSubmit("Load Question")."</noscript>".
            "<input type=button value=\"Refresh List\" onClick=\"history.go()\">".endForm();
   
   return $html;
}

function displaySelectedQuestion()
{
   global $v;
   
   $question = array(
               "qID" => 0,
               "qNum" => 0,
               "qType" => "Open",
               "qDescrip" => "",
               "possAnswers" => array());
   
   $html = "";
   if ($v["questionList"] != "") {
      for ($i = 0; $i < count(userQuestions()); $i++) {
         $question = $_SESSION["questions"][$i];
         if ($question["qNum"] == $v["questionList"]) {
            $html = createQuestionHtml($question);
            
            return $html;
         }
      }
   } else {
      $questionIndex = findFirstUnansweredIndex();
      if ($questionIndex >= 0) {
         $question = $_SESSION["questions"][$questionIndex];
         $html = createQuestionHtml($question);
            
         return $html;
      } else {
         return "<h2>You have answered all of the questions for this lesson</h2>";
      }
   }
   
   return $html;
}

function createQuestionHtml($question)
{
   if (notAnswered($question["qID"])) {
      $html = startForm("","questionForm").
            "\n<h2>".$question["qDescrip"]."</h2>\n";
      $html .= hidden("questionID",$question["qID"])."\n".
               hidden("questionType",$question["qType"])."\n";
      
      switch ($question["qType"]) {
         case "MCQ":
            for ($j = 0; $j < count($question["possAnswers"]); $j++) {
               $html .= inputCheckBox("answer",$question["possAnswers"][$j]).
                        $question["possAnswers"][$j].
                        "<br />";
            }
            $html .= "<br />".inputSubmit();
            
            break;
         case "Open":
            $html .= "Your answer: <br />".inputText("answer").
                     "<br /><br />".inputSubmit();;
            break;
         case "TFQ":
            for ($j = 0; $j < count($question["possAnswers"]); $j++) {
               $html .= inputRadio("answer",$question["possAnswers"][$j],"checked").
                        $question["possAnswers"][$j].
                        "<br />";
            }
            $html .= "<br />".inputSubmit();
            
            break;
         default:
         
            break;
      }
      $html .= endForm();
      
      //$_SESSION["answeredQuestions"][] = $question["qID"];
   } else {
      $html = "<h2>You have already answered this question</h2>\n";
   }
   
   return $html;
}

function notAnswered($qID)
{
   for($i = 0; $i < count(userAnsweredQuestions()); $i++) {
      if ($qID == $_SESSION["answeredQuestions"][$i]) {
         return false;
      }
   }
   
   return true;
}

function findFirstUnansweredIndex()
{
   $i = 0;
   while ($i < count(userQuestions())) {
      if (!in_array($_SESSION["questions"][$i]["qID"],userAnsweredQuestions())) {
         return $i;
      }
      $i++;
   }
   
   return -1;
}

?>
